<template>
  <div>
    <el-switch v-model="IsDrop" active-text="开启拖拽功能"></el-switch>
    <el-button v-if="IsDrop" type="success" @click="saveallconvert">成功按钮</el-button>
    <el-tree
      :data="Nemu"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      node-key="catId"
      show-checkbox
      :default-expanded-keys="defaultnums"
      :draggable="IsDrop"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
    >
      <!--  :expand-on-click-node="false"  这个只有在点击前面的下拉框才会出现下拉动作-->
      <!-- slot-scope 表示在后面插入
        draggable  可拖拽功能
      -->
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!-- <el-button v-if="data.catLevel <=2" type="text" size="mini" @click="() => append(data)">Append</el-button>
          <el-button v-if="data.children.length ==0"  type="text" size="mini" @click="() => remove(node, data)">Delete</el-button>-->
          <el-button
            v-if="node.level <=2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >Append</el-button>
          <el-button type="text" size="mini" @click="() => edit(node, data)">Edit</el-button>
          <el-button
            v-if="node.childNodes.length ==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >Delete</el-button>
        </span>
      </span>
    </el-tree>
    <!--visible.sync sync这个就是父子间传值的一种-->
    <el-dialog
      :close-on-click-modal="false"
      :title="titletype"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form ref="form" :model="categoryform" label-width="80px">
        <el-form-item :label="titletype">
          <el-input type="textarea" v-model="categoryform.name"></el-input>
        </el-form-item>

        <el-form-item label="计量单位">
          <el-input type="text" v-model="categoryform.productUnit"></el-input>
        </el-form-item>

        <el-form-item label="图标">
          <el-input type="text" v-model="categoryform.icon"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="changtype" v-html="buttontype"></el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      pCid:[],
      IsDrop: false,
      buttontype: "",
      EditOrAppend: "",
      Nemu: [],
      updateNodes: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      countlevel: 0,
      god: "dwdwdwd",
      defaultnums: [],
      titletype: "",
      dialogVisible: false,
      categoryform: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        icon: "",
        productCount: "",
        sort: "",
        productUnit: "",
        catId: null //这里写null 是因为插入的时候，如果是null的话，那么它就会触发自增的
      }
    };
  },
  methods: {
    handleNodeClick(data) {
      console.log(data);
    },
    getallproductcategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
        //({data}) 这里的写法相当于   取获取到的data 里面的data
      }).then(({ data }) => {
        this.Nemu = data.data;
        console.log("Nemu", this.Nemu);
      });
    },
    changtype() {
      if (this.EditOrAppend == "edit") {
        this.updatecategory();
      } else if (this.EditOrAppend == "append") {
        this.addcategory();
      }
    },
    edit(node, data) {
      this.buttontype = "修改";
      this.titletype = "修改分类";
      this.dialogVisible = true;
      this.EditOrAppend = "edit";
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get"
      }).then(({ data }) => {
        //修改什么就回显什么
        this.categoryform.catId = data.category.catId;
        this.categoryform.name = data.category.name;
        this.categoryform.icon = data.category.icon;
        this.categoryform.productUnit = data.category.productUnit;
        this.categoryform.parentCid = data.category.parentCid;
        this.categoryform.sort = data.category.sort;
        this.categoryform.catLevel = data.category.catLevel;
        this.categoryform.productCount = data.category.productCount;
        this.categoryform.showStatus = data.category.showStatus;
        console.log("edit1", data);
      });
      console.log("edit", node, data);
    },
    append(data) {
      console.log("append", data);
      this.buttontype = "添加";
      this.titletype = "添加分类";
      this.EditOrAppend = "append";
      this.dialogVisible = true;
      console.log("categoryform", this.categoryform);
      this.categoryform.name = "";
      this.categoryform.catId = null;
      this.categoryform.parentCid = data.catId;
      this.categoryform.catLevel = data.catLevel * 1 + 1;
      this.categoryform.icon = "";
      this.categoryform.productUnit = "";
      this.categoryform.showStatus = 1;
      console.log("categoryform", this.categoryform);
      console.log("append", data);
    },
    remove(node, data) {
      //node是当前元素对象，可以获取到当前元素的层级关系，是否展开，父级菜单，一级子集菜单等等
      //data就是从数据库里面查到的，在当前节点的所有内容
      console.log("remove", node, data);
      var ids = [data.catId];
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/deleteById"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            console.log("删除成功!!!", data);
            this.$message({
              message: "删除成功!!!",
              type: "success"
            });
            console.log("dataparentid", node.parent.data.catId);
            this.getallproductcategory();
            this.defaultnums = [node.parent.data.catId];
            console.log(this.defaultnums);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    addcategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.categoryform, false)
      }).then(({ data }) => {
        this.$message({
          message: "添加成功!!!",
          type: "success"
        });
        this.getallproductcategory();
        this.defaultnums = [this.categoryform.parentCid];
      });
      this.dialogVisible = false;
    },
    updatecategory() {
      var { catId, name, icon, productUnit } = this.categoryform; //解构内容 这里相当于var catId=this.categoryform.catId 依次4个
      var data = { catId, name, icon, productUnit };
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(data, false)
      }).then(({ data }) => {
        this.$message({
          message: "修改!!!",
          type: "success"
        });
        this.getallproductcategory();
        this.defaultnums = [this.categoryform.parentCid];
      });
      this.dialogVisible = false;
    },
    //判断是否允许拖动Function draggingNode是当前拖拽节点  dropNode 是放在了哪个里面还是前面还是后面，type是位置
    allowDrop(draggingNode, dropNode, type) {
      var lever = this.CountMaxLayers(draggingNode);
      //当前拖动的节点加上父节点所在的深度不大于3即可

      console.log(" dropNode ", dropNode);
      console.log(" this.countlevel ", this.countlevel);
      console.log("  dropNode.data.catLevel ", draggingNode.level);
      let deep = this.countlevel - draggingNode.level+ 1;
      this.countlevel = 0;
      console.log("deep", deep);
      if (type == "inner") {
        console.log("dropNode.level", dropNode.level);
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    CountMaxLayers(draggingNode) {
      if (draggingNode.childrenNodes != null && draggingNode.childrenNodes.length > 0) {
        console.log(
          "draggingNodedwdw===========================",
          draggingNode
        );
        console.log("this.countlev222222222231");
        for (let i = 0; i < draggingNode.childrenNodes.length; i++) {
          console.log(
            "raggingNode.children[i].catLevel113131",
            draggingNode.childrenNodes[i].level
          );
          console.log("this.countlevel,dwd,,,,,,", this.countlevel);
          if ( draggingNode.childrenNodes[i].level > this.countlevel) {
            console.log("this.countlevel,,,,,,,", this.countlevel);
            this.countlevel = draggingNode.childrenNodes[i].level;
          }
          console.log("this.countlevelresult", this.countlevel);
          this.CountMaxLayers( draggingNode.childrenNodes[i]);
        }
      } else {
        console.log(" this.countlevel = 3323232323232323;");
        this.countlevel = draggingNode.level;
      }
    },
    handleDrop(draggingNode, dropNode, dropType) {
      console.log("handleDrop", draggingNode, dropNode, dropType);
      //1.当前节点的最新父节点
      let pCid = 0;
      let siblings = [];
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        //最新顺序的兄弟节点
        siblings = dropNode.parent.childNodes;
        console.log("dropNode.parent.ChildNodes", dropNode.parent.childNodes);
        console.log("siblings111", siblings);
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
        console.log("dropNode.ChildNodes", dropNode.childNodes);
        console.log("siblings222", siblings);
      }
      //2.当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //修改当前节点的默认层级
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            //当前节点发生变化
            catLevel = siblings[i].level;
            //修改子节点的层级
            this.updateChildrenNodelevel(siblings[i]);
          }
          //如果是遍历的当前正在拖拽的节点，这里还要改父ID
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel
          });
        } else {
          //兄弟的只需要改顺序
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      this.pCid.push(pCid)
    },
    saveallconvert() {
      console.log("this.updateNodes", this.updateNodes);
      this.$http({
        url: this.$http.adornUrl("/product/category/update/list"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.getallproductcategory();
        this.defaultnums = this.pCid;
        this.countlevel = 0;
        this.updateNodes = [];
        console.log(data);
      });
    },
    updateChildrenNodelevel(node) {
      console.log("nodenodenodenode", node);
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level
          });
          this.updateChildrenNodelevel(node.childNodes[i]);
        }
      }
    }
  },
  created() {
    this.getallproductcategory();
  },
  mounted() {},
  activited() {},
  update() {},
  beforeRouteUpdate() {},
  filter: {},
  computed: {},
  watch: {}
};
</script>

<style >
</style>

q3